package com.wts.client.utils;

import java.io.UnsupportedEncodingException;

public class StringToBytes {

	/**字符串编码
	 * @param str
	 * @return
	 */
	public static String bytes2Hex(String str) {
		byte[] src;
		try {
			src = str.getBytes("utf8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		if (src == null || src.length <= 0) {
			return null;
		}
		char[] res = new char[src.length * 2]; // 每个byte对应两个字符
		final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		for (int i = 0, j = 0; i < src.length; i++) {
			res[j++] = hexDigits[src[i] >> 4 & 0x0f]; // 先存byte的高4位
			res[j++] = hexDigits[src[i] & 0x0f]; // 再存byte的低4位
		}

		return new String(res);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		String bytestr = bytes2Hex("阿斯頓發射點發給");

		System.out.println(bytestr);

		System.out.println(hex2Bytes(bytestr));
	}

	/**字符串解码
	 * @param hexString
	 * @return
	 */
	public static String hex2Bytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] bytes = new byte[length];
		String hexDigits = "0123456789abcdef";
		for (int i = 0; i < length; i++) {
			int pos = i * 2; // 两个字符对应一个byte
			int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
			int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
			if (h == -1 || l == -1) { // 非16进制字符
				return null;
			}
			bytes[i] = (byte) (h | l);
		}
		try {
			return new String(bytes, "utf8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
